import { FBXLoader } from '../lib/FBXLoader.js';
// ESM: 引入GLTFLoader
import * as THREE from '../lib/three.module.js';

const loader = new FBXLoader();

class Gallery {
    constructor(data) {
        this.data = data;
        this.currentRoomIndex = 0;
        this.moveForward = false;
        this.moveBackward = false;
        this.moveLeft = false;
        this.moveRight = false;
        this.moveSpeed = 0.1;
        this.rotationSpeed = 0.1; // 新增：转向速度
        this.targetAvatarYaw = 0; // 新增：目标朝向
        this.lastMoveDirection = null; // 新增：记录上一次的移动方向
        this.animationState = 'idle'; // 新增：动画状态管理
        this.lastMoveTime = 0; // 新增：记录最后一次移动的时间
        this.idleTimeout = 500; // 新增：静止超时时间（毫秒）
        this.idleCheckTimer = null; // 新增：静止检查定时器
        this.scene = new THREE.Scene();
        // 设置浅灰色背景
        this.scene.background = new THREE.Color(0x808080);
        this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        const currentRoom = this.data.rooms[this.currentRoomIndex];
        // 计算房间中心高度
        const centerY = 3.0; // 更高的视角
        // 自动根据第一幅画作所在墙体调整相机位置和朝向
        const artworkWall = currentRoom.artworks[0]?.position.wall || 'north';
        let camPos, camYaw;
        switch (artworkWall) {
            case 'north':
                camPos = [0, centerY, currentRoom.size.depth / 2 - 2];
                camYaw = Math.PI;
                break;
            case 'south':
                camPos = [0, centerY, -currentRoom.size.depth / 2 + 2];
                camYaw = 0;
                break;
            case 'east':
                camPos = [-currentRoom.size.width / 2 + 2, centerY, 0];
                camYaw = -Math.PI / 2;
                break;
            case 'west':
                camPos = [currentRoom.size.width / 2 - 2, centerY, 0];
                camYaw = Math.PI / 2;
                break;
            default:
                camPos = [0, centerY, currentRoom.size.depth / 3];
                camYaw = 0;
        }
        // 在init()方法中，初始化相机时将z坐标拉远
        // 找到this.camera.position.set(...camPos);，将z设为15
        if (camPos.length === 3) {
            camPos[2] = 15; // 拉远z坐标
        }
        this.camera.position.set(...camPos);
        this.yaw = camYaw;
        this.pitch = 0;
        this.mouseSensitivity = 0.002;
        this.isRightMouseDown = false; // 新增：右键按下标志
        this.isJumping = false; // 是否正在跳跃
        this.jumpVelocity = 0; // 跳跃速度
        this.gravity = -0.015; // 重力加速度
        this.jumpSpeed = 0.32; // 跳跃初速度
        this.renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
        this.raycaster = new THREE.Raycaster();
        this.mouse = new THREE.Vector2();
        this.artworkMeshes = new Map();
        this.clock = new THREE.Clock(); // 新增：动画驱动时钟
        this.avatarYaw = this.yaw; // 新增：小人当前朝向
        this.init();
    }

    init() {
        this.renderer.setSize(window.innerWidth, window.innerHeight);
        this.renderer.setPixelRatio(window.devicePixelRatio);
        this.renderer.shadowMap.enabled = true;
        const container = document.getElementById('container');
        container.appendChild(this.renderer.domElement);
        // 重新设置灯光
        // 清除现有灯光
        this.scene.children.forEach(child => {
            if (child.isLight) {
                this.scene.remove(child);
            }
        });

        // 添加新的灯光设置
        // 环境光
        const ambientLight = new THREE.AmbientLight(0xffffff, 2.0); // 强度提升
        this.scene.add(ambientLight);

        // 主方向光（正面）
        const mainLight = new THREE.DirectionalLight(0xffffff, 2.0); // 强度提升
        mainLight.position.set(0, 5, 10);
        mainLight.castShadow = true;
        mainLight.shadow.mapSize.width = 2048;
        mainLight.shadow.mapSize.height = 2048;
        this.scene.add(mainLight);

        // 补充光源（左侧）
        const leftLight = new THREE.DirectionalLight(0xffffff, 1.2); // 强度提升
        leftLight.position.set(-10, 5, 0);
        this.scene.add(leftLight);

        // 补充光源（右侧）
        const rightLight = new THREE.DirectionalLight(0xffffff, 1.2); // 强度提升
        rightLight.position.set(10, 5, 0);
        this.scene.add(rightLight);

        // 补充光源（顶部）
        const topLight = new THREE.DirectionalLight(0xffffff, 0.8); // 强度提升
        topLight.position.set(0, 10, 0);
        this.scene.add(topLight);
        
        // 四个角落的点光源 - 提供均匀照明
        const cornerLights = [
            { pos: [5, 6, 5], color: 0xffffff },
            { pos: [-5, 6, 5], color: 0xffffff },
            { pos: [5, 6, -5], color: 0xffffff },
            { pos: [-5, 6, -5], color: 0xffffff }
        ];
        
        cornerLights.forEach(light => {
            const pointLight = new THREE.PointLight(light.color, 1.2, 15); // 强度提升
            pointLight.position.set(...light.pos);
            this.scene.add(pointLight);
        });
        
        // 地面反射光 - 模拟地面反射
        const groundLight = new THREE.DirectionalLight(0xffffff, 0.6); // 强度提升
        groundLight.position.set(0, -1, 0);
        this.scene.add(groundLight);
        // 已移除PointerLock相关代码
        window.addEventListener('keydown', this.onKeyDown.bind(this));
        window.addEventListener('keyup', this.onKeyUp.bind(this));
        document.addEventListener('mousedown', this.onMouseDown.bind(this));
        document.addEventListener('mouseup', this.onMouseUp.bind(this));
        document.addEventListener('mousemove', this.onMouseMove.bind(this));
        this.renderer.domElement.addEventListener('wheel', this.onMouseWheel.bind(this), { passive: false });
        // 新增：阻止右键菜单弹出
        this.renderer.domElement.addEventListener('contextmenu', function(e) { e.preventDefault(); });
        window.addEventListener('resize', this.onWindowResize.bind(this));
        // 新增：点击画作弹窗详情
        this.renderer.domElement.addEventListener('click', this.onCanvasClick.bind(this));
        this.createRoom(this.currentRoomIndex);
        this.animate();
        // 加载FBX小人
        // console.log('FBXLoader is', FBXLoader);
        // const loader = new FBXLoader();
        
        loader.load('models/Walking.fbx', (object) => {
            // 调整缩放比例
            object.scale.set(0.008, 0.008, 0.008);
            object.position.set(0, 0, 0);

            this.scene.add(object);
            this.avatar = object;
            this.avatar.visible = false; // 初始化时默认隐藏小人
            var northOffset = 10;
            this.avatar.position.set(0, 0, 0);
            

            // 动画系统
            if (object.animations && object.animations.length > 0) {
                // 检查动画信息
                console.log('Animation details:', {
                    name: object.animations[0].name,
                    duration: object.animations[0].duration,
                    tracks: object.animations[0].tracks.map(track => track.name)
                });
                
                // 创建动画混合器
                this.mixer = new THREE.AnimationMixer(object);
                
                // 创建动画剪辑
                const walkClip = object.animations[0];
                
                // 创建动画动作
                this.walkAction = this.mixer.clipAction(walkClip);
                
                // 设置动画循环模式
                this.walkAction.setLoop(THREE.LoopRepeat);
                
                // 设置动画权重
                this.walkAction.weight = 1;
                
                // 设置动画淡入淡出时间
                this.walkAction.fadeIn(0.3);
                
                // 设置动画播放速度
                this.walkAction.timeScale = 1.0;
                
                // 设置动画混合模式
                this.walkAction.setEffectiveWeight(1);
                
                // 确保动画从头开始播放
                this.walkAction.reset();
                
                // 初始化为暂停状态
                this.walkAction.play();
                this.walkAction.paused = true;
                
                // 初始化动画状态
                this.mixer.update(0);
                
                // 确保小人初始位置在房间中心
                const initialAvatarPos = new THREE.Vector3(0, 0, 0); // 房间中心
                this.lastMovePosition = initialAvatarPos.clone();
                if (this.avatar) {
                    this.avatar.position.copy(initialAvatarPos);
                }
                // 相机位置与小人一致，但保持一定高度
                const cameraPos = initialAvatarPos.clone();
                cameraPos.y = 3.0; // 相机高度
                cameraPos.z = cameraPos.z + 2.5; // 相机稍微向后方移动
                this.camera.position.set(cameraPos.x, cameraPos.y, cameraPos.z);
                
                // 初始化用户移动标志
                this.hasUserMoved = false;
                
                // 创建一个空闲姿势（静止姿势）
                // 尝试找到一个更合适的静止姿势帧
                const clipDuration = walkClip.duration;
                
                // 使用页面加载时的初始状态作为静止姿势
                // 这通常是FBX模型的默认T-pose，但我们需要找到胳膊自然下垂的帧
                this.idlePose = {
                    time: 0  // 先使用开始帧，然后我们会找到正确的帧
                };
                
                // 创建多个可能的静止姿势供测试
                this.idlePoses = [
                    { time: 0, name: "开始帧(T-pose)" },
                    { time: clipDuration * 0.25, name: "1/4帧" },
                    { time: clipDuration * 0.5, name: "中间帧" },
                    { time: clipDuration * 0.75, name: "3/4帧" },
                    // 添加更多精确的姿势点
                    { time: clipDuration * 0.1, name: "10%帧" },
                    { time: clipDuration * 0.2, name: "20%帧" },
                    { time: clipDuration * 0.3, name: "30%帧" },
                    { time: clipDuration * 0.4, name: "40%帧" },
                    { time: clipDuration * 0.6, name: "60%帧" },
                    { time: clipDuration * 0.7, name: "70%帧" },
                    { time: clipDuration * 0.8, name: "80%帧" },
                    { time: clipDuration * 0.9, name: "90%帧" }
                ];
                
                // 当前使用的静止姿势索引 - 先使用开始帧
                this.currentIdlePoseIndex = 0;
                
                // 设置当前静止姿势
                this.idlePose = this.idlePoses[this.currentIdlePoseIndex];
                
                // 初始化为静止姿势
                this.walkAction.time = this.idlePose.time;
                
                // 保存当前位置（如果小人已存在）
                const currentPosition = this.avatar ? this.avatar.position.clone() : null;
                
                this.mixer.update(0);
                
                // 恢复位置（如果小人已存在）
                if (currentPosition && this.avatar) {
                    this.avatar.position.copy(currentPosition);
                }
                
                // 打印当前使用的静止姿势
                console.log('使用静止姿势:', this.idlePose.name, '时间:', this.idlePose.time);
                console.log('注意：如果这个姿势不对，请使用 startPoseTest() 来找到正确的姿势');
                
                // 添加切换静止姿势的方法（可以通过控制台调用）
                this.switchIdlePose = (index) => {
                    if (index >= 0 && index < this.idlePoses.length) {
                        this.currentIdlePoseIndex = index;
                        this.idlePose = this.idlePoses[index];
                        
                        // 如果当前是静止状态，立即应用新姿势
                        if (this.walkAction.paused) {
                            // 保存当前位置
                            const currentPosition = this.avatar ? this.avatar.position.clone() : null;
                            
                            this.walkAction.time = this.idlePose.time;
                            this.mixer.update(0);
                            
                            // 恢复位置
                            if (currentPosition && this.avatar) {
                                this.avatar.position.copy(currentPosition);
                            }
                        }
                        
                        console.log('切换到静止姿势:', this.idlePose.name, '时间:', this.idlePose.time);
                        return true;
                    }
                    return false;
                };
                
                // 将方法暴露到全局，方便调试
                window.switchIdlePose = (index) => this.switchIdlePose(index);
                
                // 添加强制重置静止姿势的方法
                this.resetToIdlePose = () => {
                    if (this.idlePose && this.walkAction) {
                        console.log('强制重置到静止姿势');
                        
                        // 保存当前位置
                        const currentPosition = this.avatar ? this.avatar.position.clone() : null;
                        
                        this.walkAction.paused = true;
                        this.walkAction.time = this.idlePose.time;
                        this.mixer.update(0);
                        
                        // 恢复位置
                        if (currentPosition && this.avatar) {
                            this.avatar.position.copy(currentPosition);
                        }
                        
                        return true;
                    }
                    return false;
                };
                
                // 将重置方法暴露到全局
                window.resetToIdlePose = () => this.resetToIdlePose();
                
                // 添加测试所有姿势的方法
                this.testAllPoses = () => {
                    console.log('开始测试所有姿势...');
                    for (let i = 0; i < this.idlePoses.length; i++) {
                        setTimeout(() => {
                            this.switchIdlePose(i);
                            console.log(`测试姿势 ${i}: ${this.idlePoses[i].name}`);
                        }, i * 2000); // 每2秒切换一个姿势
                    }
                };
                
                // 将测试方法暴露到全局
                window.testAllPoses = () => this.testAllPoses();
                
                // 添加快速测试静止姿势的方法
                this.testIdlePose = (index) => {
                    if (index >= 0 && index < this.idlePoses.length) {
                        console.log('测试静止姿势:', this.idlePoses[index].name);
                        
                        // 保存当前位置
                        const currentPosition = this.avatar ? this.avatar.position.clone() : null;
                        
                        this.walkAction.paused = true;
                        this.walkAction.time = this.idlePoses[index].time;
                        this.walkAction.setEffectiveWeight(1);
                        this.mixer.update(0);
                        
                        // 恢复位置
                        if (currentPosition && this.avatar) {
                            this.avatar.position.copy(currentPosition);
                        }
                        
                        return true;
                    }
                    return false;
                };
                
                // 将测试方法暴露到全局
                window.testIdlePose = (index) => this.testIdlePose(index);
                
                // 添加实时测试方法，可以连续切换姿势
                this.startPoseTest = () => {
                    console.log('开始实时姿势测试，每2秒切换一个姿势...');
                    let currentIndex = 0;
                    this.poseTestInterval = setInterval(() => {
                        this.testIdlePose(currentIndex);
                        console.log(`当前测试姿势 ${currentIndex}: ${this.idlePoses[currentIndex].name}`);
                        currentIndex = (currentIndex + 1) % this.idlePoses.length;
                    }, 2000);
                };
                
                this.stopPoseTest = () => {
                    if (this.poseTestInterval) {
                        clearInterval(this.poseTestInterval);
                        console.log('停止姿势测试');
                    }
                };
                
                // 将测试方法暴露到全局
                window.startPoseTest = () => this.startPoseTest();
                window.stopPoseTest = () => this.stopPoseTest();
                
                // 打印提示信息
                // console.log('调试提示: 可以通过控制台调用 switchIdlePose(0-11) 来切换不同的静止姿势');
                // console.log('调试提示: 可以通过控制台调用 resetToIdlePose() 来强制重置到静止姿势');
                // console.log('调试提示: 可以通过控制台调用 testAllPoses() 来测试所有姿势');
                // console.log('调试提示: 可以通过控制台调用 testIdlePose(0-11) 来快速测试单个姿势');
                // console.log('调试提示: 可以通过控制台调用 startPoseTest() 来开始实时测试，stopPoseTest() 来停止');
                // console.log('建议: 现在使用1/4帧，如果不对请尝试其他帧');
            }

            // 计算footOffset
            const box = new THREE.Box3().setFromObject(object);
            const height = box.max.y - box.min.y;
            this.avatar.userData.footOffset = box.min.y;
            this.avatar.userData.height = height;

            // 打印完整的加载信息
            console.log('Avatar loaded:', {
                totalMeshes: object.children.filter(child => child.isMesh).length,
                animations: object.animations ? object.animations.length : 0,
                boundingBox: {
                    min: box.min.toArray(),
                    max: box.max.toArray()
                },
                scale: object.scale.toArray()
            });
        });

        //在展厅中间加载一个起汽车模型，模型文件为modelNew.fbx

        


        loader.load('models/modelNew.fbx', (car) => {
            console.log('car loaded:', car);
            // 缩小模型
            car.scale.set(0.01, 0.01, 0.01);
            // 计算包围盒，将底部放到y=0，并向左移动x=-5
            const box = new THREE.Box3().setFromObject(car);
            const minY = box.min.y;
            car.position.set(-2, -minY, 0); // x=-5，左移
            this.scene.add(car);
            this.carModel = car;
        }, undefined, (error) => {
            console.error('Error loading car model:', error);
        });

        //TODO 材质使用的dds格式，tree.js默认不支持需要转换为png，然后再再改fbx引用
        loader.load('models/YU7.fbx', (car) => {
            console.log('car loaded:', car);
            // 缩小模型
            car.scale.set(0.005, 0.005, 0.005);
            // 计算包围盒，将底部放到y=0，并向左移动x=-5
            const box = new THREE.Box3().setFromObject(car);
            const minY = box.min.y;
            car.position.set(3, -minY, 0); // x=-5，左移
            this.scene.add(car);
            this.carModel = car;
        }, undefined, (error) => {
            console.error('Error loading car model:', error);
        });
    }

    onKeyDown(event) {
        // console.log('KeyDown:', event.code);
        switch (event.code) {
            case 'KeyW': this.moveForward = true; break;
            case 'KeyS': this.moveBackward = true; break;
            case 'KeyA': this.moveLeft = true; break;
            case 'KeyD': this.moveRight = true; break;
            // 添加数字键1-4切换静止姿势
            case 'Digit1': if(this.switchIdlePose) this.switchIdlePose(0); break;
            case 'Digit2': if(this.switchIdlePose) this.switchIdlePose(1); break;
            case 'Digit3': if(this.switchIdlePose) this.switchIdlePose(2); break;
            case 'Digit4': if(this.switchIdlePose) this.switchIdlePose(3); break;
            case 'Digit5': if(this.switchIdlePose) this.switchIdlePose(4); break;
            case 'Digit6': if(this.switchIdlePose) this.switchIdlePose(5); break;
            case 'Digit7': if(this.switchIdlePose) this.switchIdlePose(6); break;
            case 'Digit8': if(this.switchIdlePose) this.switchIdlePose(7); break;
            case 'Digit9': if(this.switchIdlePose) this.switchIdlePose(8); break;
            case 'Digit0': if(this.switchIdlePose) this.switchIdlePose(9); break;
            case 'Minus': if(this.switchIdlePose) this.switchIdlePose(10); break;
            case 'Equal': if(this.switchIdlePose) this.switchIdlePose(11); break;
            case 'Space': this.tryJump(); break;
        }
    }
    onKeyUp(event) {
        switch (event.code) {
            case 'KeyW': this.moveForward = false; break;
            case 'KeyS': this.moveBackward = false; break;
            case 'KeyA': this.moveLeft = false; break;
            case 'KeyD': this.moveRight = false; break;
        }
    }
    onMouseDown(event) {
        if (event.button === 2) { // 右键
            this.isRightMouseDown = true;
        }
    }
    onMouseUp(event) {
        if (event.button === 2) {
            this.isRightMouseDown = false;
        }
    }
    onMouseMove(event) {
        if (!this.isRightMouseDown) return;
        this.yaw -= event.movementX * this.mouseSensitivity;
        this.pitch -= event.movementY * this.mouseSensitivity;
        this.pitch = Math.max(-Math.PI/2, Math.min(Math.PI/2, this.pitch));
    }
    onMouseWheel(event) {
        event.preventDefault();
        // 缩放：调整fov，限制范围在20~100度（原来是20~100）
        this.camera.fov += event.deltaY * 0.05;
        this.camera.fov = Math.max(20, Math.min(100, this.camera.fov)); // 上限改为150
        this.camera.updateProjectionMatrix();
        console.log('当前相机fov:', this.camera.fov);
    }
    updateCameraRotation() {
        // 计算相机方向
        const direction = new THREE.Vector3();
        direction.x = Math.sin(this.yaw) * Math.cos(this.pitch);
        direction.y = Math.sin(this.pitch);
        direction.z = Math.cos(this.yaw) * Math.cos(this.pitch);
        this.camera.lookAt(
            this.camera.position.x + direction.x,
            this.camera.position.y + direction.y,
            this.camera.position.z + direction.z
        );
    }
    tryJump() {
        // 只有在地面上才能跳跃
        const room = this.data.rooms[this.currentRoomIndex];
        const minY = 3.0;
        console.log('tryJump:', this.isJumping, this.camera.position.y, minY);
        if (!this.isJumping && this.camera.position.y <= minY + 0.05) {
            this.isJumping = true;
            this.jumpVelocity = this.jumpSpeed;
            console.log('Jump!');
        }
    }
    updateMovement() {
        // 获取当前房间尺寸和边界
        const room = this.data.rooms[this.currentRoomIndex];
        const halfW = room.size.width / 2 - 0.5; // 预留0.5米缓冲，防止贴墙
        const halfD = room.size.depth / 2 - 0.5;
        const minY = 3.0; // 更高的视角
        const maxY = room.size.height - 0.5; // 天花板下方0.5米

        // WASD移动
        const direction = new THREE.Vector3();
        this.camera.getWorldDirection(direction);
        direction.y = 0;
        direction.normalize();
        const right = new THREE.Vector3();
        right.crossVectors(direction, new THREE.Vector3(0, 1, 0));
        const moveVector = new THREE.Vector3(0, 0, 0);
        if (this.moveForward) moveVector.add(direction.clone().multiplyScalar(this.moveSpeed));
        if (this.moveBackward) moveVector.add(direction.clone().multiplyScalar(-this.moveSpeed));
        if (this.moveRight) moveVector.add(right.clone().multiplyScalar(this.moveSpeed));
        if (this.moveLeft) moveVector.add(right.clone().multiplyScalar(-this.moveSpeed));

        // 计算目标位置
        const nextPos = this.camera.position.clone().add(moveVector);
        // 限制在房间内
        nextPos.x = Math.max(-halfW, Math.min(halfW, nextPos.x));
        nextPos.y = Math.max(minY, Math.min(maxY, nextPos.y));
        nextPos.z = Math.max(-halfD, Math.min(halfD, nextPos.z));
        this.camera.position.copy(nextPos);

        // 处理跳跃和重力
        if (this.isJumping) {
            this.camera.position.y += this.jumpVelocity;
            this.jumpVelocity += this.gravity;
            if (this.camera.position.y <= minY) {
                this.camera.position.y = minY;
                this.isJumping = false;
                this.jumpVelocity = 0;
            } else if (this.camera.position.y > maxY) {
                this.camera.position.y = maxY;
                this.jumpVelocity = 0;
            }
        }
        
        // 删除这里的动画控制，统一在animate方法中处理
    }
    
    animate() {
        // 一次性初始化 fov
        if (!this._fovInitialized) {
            this.camera.fov = 100;
            this.pitch = -0.3; // 向下看约17度
            this.updateCameraRotation(); // 应用新的俯仰角
            this.camera.updateProjectionMatrix();
            // console.log('强制初始化视角:', this.camera.fov, '俯仰角:', this.pitch);
            this._fovInitialized = true;
        }
        
        requestAnimationFrame(this.animate.bind(this));
        
        // 更新移动和相机
        this.updateMovement();
        this.updateCameraRotation();
        
        // 更新小人位置和动画
        if (this.avatar && this.mixer) {
            const delta = this.clock.getDelta();
            
            // 判断是否在移动
            const isMoving = this.moveForward || this.moveBackward || this.moveLeft || this.moveRight;
            
            // 计算当前移动方向
            let currentMoveDirection = null;
            if (this.moveForward) currentMoveDirection = 'forward';
            else if (this.moveBackward) currentMoveDirection = 'backward';
            else if (this.moveLeft) currentMoveDirection = 'left';
            else if (this.moveRight) currentMoveDirection = 'right';
            
            // 检查方向是否发生变化
            const directionChanged = this.lastMoveDirection !== null && this.lastMoveDirection !== currentMoveDirection;
            
            // 简化的动画控制逻辑
            if (isMoving) {
                // 记录移动时间
                this.lastMoveTime = Date.now();
                
                // 如果方向发生变化，重置动画
                if (directionChanged) {
                    console.log('方向改变，重置动画 - 从', this.lastMoveDirection, '到', currentMoveDirection);
                    // 先暂停当前动画
                    this.walkAction.paused = true;
                    // 重置动画
                    this.walkAction.reset();
                    // 重新开始播放
                    this.walkAction.paused = false;
                    this.walkAction.fadeIn(0.2);
                    this.walkAction.play();
                    
                    // 确保动画立即生效，但不影响位置
                    // this.mixer.update(0); // 移除这行
                    this.animationState = 'moving';
                }
                
                // 确保动画正在播放
                if (this.walkAction.paused) {
                    // console.log('开始移动动画');
                    this.walkAction.paused = false;
                    this.walkAction.reset();
                    this.walkAction.fadeIn(0.2);
                    this.walkAction.play();
                    this.animationState = 'moving';
                }
                
                // 更新上一次移动方向
                this.lastMoveDirection = currentMoveDirection;
            } else {
                // 检查是否静止超过指定时间
                const timeSinceLastMove = Date.now() - this.lastMoveTime;
                if (timeSinceLastMove > this.idleTimeout && !this.walkAction.paused) {
                    // console.log('静止超时，停止移动');
                    // 只停止移动，不做任何动画或姿态重置
                    this.walkAction.paused = true;
                    this.animationState = 'idle';
                }
                
                // 重置移动方向记录
                this.lastMoveDirection = null;
            }
            
            // 更新动画混合器
            this.mixer.update(delta);
            
            // 计算移动方向
            let moveYaw = null;
            if (this.moveForward) moveYaw = this.yaw;
            else if (this.moveBackward) moveYaw = this.yaw + Math.PI;
            else if (this.moveLeft) moveYaw = this.yaw + Math.PI / 2;
            else if (this.moveRight) moveYaw = this.yaw - Math.PI / 2;

            // 更新目标朝向
            if (moveYaw !== null) {
                this.targetAvatarYaw = moveYaw;
            }

            // 平滑插值更新实际朝向
            if (isMoving) {
                // 计算当前朝向和目标朝向之间的最短角度
                let angleDiff = ((this.targetAvatarYaw - this.avatarYaw) + Math.PI * 3) % (Math.PI * 2) - Math.PI;
                
                // 使用线性插值更新朝向
                if (Math.abs(angleDiff) > 0.01) {
                    this.avatarYaw += angleDiff * this.rotationSpeed;
                    // 确保角度在 0 到 2π 之间
                    this.avatarYaw = ((this.avatarYaw % (Math.PI * 2)) + Math.PI * 2) % (Math.PI * 2);
                }
            }

            // 计算相机前方向量
            const cameraForward = new THREE.Vector3();
            this.camera.getWorldDirection(cameraForward);
            cameraForward.y = 0; // 忽略垂直分量
            cameraForward.normalize();

            // 计算小人位置 - 使用相机前方向量
            const avatarPos = this.camera.position.clone();
            avatarPos.add(cameraForward.clone().multiplyScalar(2.5)); // 保持在相机前方2.5米
            // 设置固定高度
            const room = this.data.rooms[this.currentRoomIndex];
            avatarPos.y = 0; // 地面高度

            // 限制在房间范围内
            const halfW = room.size.width / 2 - 1.0; // 增加边界缓冲
            const halfD = room.size.depth / 2 - 1.0; // 统一边界缓冲区
            // 调整边界计算，不考虑北偏移的影响
            avatarPos.x = Math.max(-halfW, Math.min(halfW, avatarPos.x));
            avatarPos.z = Math.max(-halfD, Math.min(halfD, avatarPos.z));

            // 根据移动状态决定位置更新方式
            if (this.avatar) {
                if (isMoving) {
                    this.avatar.position.copy(avatarPos);
                    this.lastMovePosition = avatarPos.clone();
                    this._hasLoggedStop = false; // 只要移动就重置日志标志
                    this.hasUserMoved = true; // 标记用户已经移动过
                } else {
                    // 只有在用户已经移动过的情况下，才使用停止逻辑
                    if (this.hasUserMoved && this.lastMovePosition) {
                        // 直接使用相机当前位置，不做额外处理
                        this.avatar.position.copy(avatarPos);
                        
                        if (!this._hasLoggedStop) {
                            // console.log('停止状态 - 使用相机当前位置:', avatarPos.x.toFixed(2), avatarPos.y.toFixed(2), avatarPos.z.toFixed(2));
                            // console.log('停止状态 - 小人当前位置:', this.avatar.position.x.toFixed(2), this.avatar.position.y.toFixed(2), this.avatar.position.z.toFixed(2));
                            // console.log('停止状态 - 小人朝向:', (this.avatarYaw * 180 / Math.PI).toFixed(2) + '°');
                            // console.log('停止状态 - 动画状态:', this.animationState, '动画暂停:', this.walkAction.paused);
                            // console.log('停止状态 - 动画时间:', this.walkAction.time.toFixed(2));
                            this._hasLoggedStop = true;
                        }
                    }
                    // 不要 return，让后续渲染和UI更新继续执行
                }
            }

            // 检查小人是否在相机视锥体内
            const frustum = new THREE.Frustum();
            const matrix = new THREE.Matrix4().multiplyMatrices(
                this.camera.projectionMatrix,
                this.camera.matrixWorldInverse
            );
            frustum.setFromProjectionMatrix(matrix);

            // 创建一个包围球来检查可见性
            const avatarCenter = this.avatar.position.clone();
            avatarCenter.y += 1; // 调整到小人中心高度
            const boundingSphere = new THREE.Sphere(avatarCenter, 1);

            // 更新朝向
            this.avatar.rotation.y = this.avatarYaw;

            // 确保小人可见
            // this.avatar.visible = true;
            this.avatar.traverse((child) => {
                if (child.isMesh) {
                    child.visible = true;
                }
            });

            // 调试输出
            // console.log('Avatar debug:', {
            //     position: {
            //         x: avatarPos.x.toFixed(2),
            //         y: avatarPos.y.toFixed(2),
            //         z: avatarPos.z.toFixed(2)
            //     },
            //     camera: {
            //         x: this.camera.position.x.toFixed(2),
            //         y: this.camera.position.y.toFixed(2),
            //         z: this.camera.position.z.toFixed(2)
            //     },
            //     direction: {
            //         x: cameraForward.x.toFixed(2),
            //         y: cameraForward.y.toFixed(2),
            //         z: cameraForward.z.toFixed(2)
            //     },
            //     inFrustum: frustum.intersectsSphere(boundingSphere),
            //     isMoving: isMoving,
            //     yaw: (this.avatarYaw * 180 / Math.PI).toFixed(2) + '°'
            // });
        }

        // 渲染场景
        this.renderer.render(this.scene, this.camera);

        // 更新指南针UI
        this.updateCompass();
    }

    // 新增：更新指南针UI的独立函数
    updateCompass() {
        const compassArrow = document.querySelector('#direction-indicator .arrow');
        if (compassArrow) {
            const deg = -this.yaw * 180 / Math.PI + 180;
            compassArrow.style.transform = `translateX(-50%) rotate(${deg}deg)`;
        }

        const compassNeedle = document.querySelector('#direction-indicator .compass-needle');
        if (compassNeedle) {
            const deg = -this.yaw * 180 / Math.PI + 180;
            compassNeedle.style.transform = `rotate(${deg}deg)`;
        }
    }
    createRoom(roomIndex) {
        this.clearRoom();
        const room = this.data.rooms[roomIndex];
        const { width, height, depth } = room.size;
        const geometry = new THREE.BoxGeometry(width, height, depth);

        // 加载纹理
        const textureLoader = new THREE.TextureLoader();
        
        // 加载大理石地板纹理
        const floorTexture = textureLoader.load('textures/floor.jpg', 
            () => console.log('Floor texture loaded'),
            undefined,
            err => console.error('Floor texture error:', err)
        );
        floorTexture.wrapS = THREE.RepeatWrapping;
        floorTexture.wrapT = THREE.RepeatWrapping;
        floorTexture.repeat.set(4, 4); // 调整纹理重复次数
        
        // 加载天花板纹理
        const ceilingTexture = textureLoader.load('textures/ceiling.jpg',
            () => console.log('Ceiling texture loaded'),
            undefined,
            err => console.error('Ceiling texture error:', err)
        );
        ceilingTexture.wrapS = THREE.RepeatWrapping;
        ceilingTexture.wrapT = THREE.RepeatWrapping;
        ceilingTexture.repeat.set(3, 3); // 调整纹理重复次数

        // 加载墙面纹理（每面墙单独加载，避免clone导致黑色）
        const wallTextureRight = textureLoader.load('textures/wall.jpg',
            () => console.log('Wall texture loaded: right'),
            undefined,
            err => console.error('Wall texture error: right', err)
        );
        wallTextureRight.wrapS = THREE.RepeatWrapping;
        wallTextureRight.wrapT = THREE.RepeatWrapping;
        wallTextureRight.repeat.set(2, 1);

        const wallTextureLeft = textureLoader.load('textures/wall.jpg',
            () => console.log('Wall texture loaded: left'),
            undefined,
            err => console.error('Wall texture error: left', err)
        );
        wallTextureLeft.wrapS = THREE.RepeatWrapping;
        wallTextureLeft.wrapT = THREE.RepeatWrapping;
        wallTextureLeft.repeat.set(2, 1);

        const wallTextureFront = textureLoader.load('textures/wall.jpg',
            () => console.log('Wall texture loaded: front'),
            undefined,
            err => console.error('Wall texture error: front', err)
        );
        wallTextureFront.wrapS = THREE.RepeatWrapping;
        wallTextureFront.wrapT = THREE.RepeatWrapping;
        wallTextureFront.repeat.set(2, 1);

        const wallTextureBack = textureLoader.load('textures/wall.jpg',
            () => console.log('Wall texture loaded: back'),
            undefined,
            err => console.error('Wall texture error: back', err)
        );
        wallTextureBack.wrapS = THREE.RepeatWrapping;
        wallTextureBack.wrapT = THREE.RepeatWrapping;
        wallTextureBack.repeat.set(2, 1);

        // 材质数组 [右，左，上，下，前，后]
        const materials = [
            new THREE.MeshBasicMaterial ({ color: 0xffffff, map: wallTextureRight, side: THREE.BackSide }),
            new THREE.MeshBasicMaterial ({ color: 0xffffff, map: wallTextureLeft, side: THREE.BackSide }),
            new THREE.MeshBasicMaterial ({ color: 0xffffff, map: ceilingTexture, side: THREE.BackSide }),
            new THREE.MeshBasicMaterial ({ color: 0xffffff, map: floorTexture, side: THREE.BackSide }),
            new THREE.MeshBasicMaterial ({ color: 0xffffff, map: wallTextureFront, side: THREE.BackSide }),
            new THREE.MeshBasicMaterial ({ color: 0xffffff, map: wallTextureBack, side: THREE.BackSide })
        ];

        // 为所有材质添加重复和平滑设置
        materials.forEach(material => {
            if (material.map) {
                material.map.minFilter = THREE.LinearFilter;
                material.map.magFilter = THREE.LinearFilter;
            }
        });
        const roomMesh = new THREE.Mesh(geometry, materials);
        roomMesh.position.set(0, height / 2, 0);
        roomMesh.receiveShadow = true;
        roomMesh.castShadow = true;
        this.scene.add(roomMesh);
        this.addArtworks(room);
        const roomTitle = document.querySelector('.room-title');
        if (roomTitle) roomTitle.textContent = room.name;
    }
    addArtworks(room) {
        // 1. 获取北面墙第一个画作的高度作为标准高度
        let standardY = 3.5; // 默认高度
        const northArtwork = room.artworks.find(a => a.position.wall === 'north');
        if (northArtwork) {
            standardY = northArtwork.position.y;
        }
        // 2. 每面墙均匀分布3个画框
        const wallNames = ['north', 'south', 'east', 'west'];
        const defaultFrameWidth = 3; // 默认画框宽度
        const defaultFrameHeight = 2; // 默认画框高度
        const margin = 5; // 画框之间的间距（加大）
        wallNames.forEach(wall => {
            const artworksOnWall = room.artworks.filter(a => a.position.wall === wall);
            // 创建默认相框列表
            const defaultFrames = [];
            for (let i = 0; i < 3; i++) {
                // 计算每个画框的中心位置
                let x = 0, y = standardY, z = 0;
                if (wall === 'north' || wall === 'south') {
                    x = (i - 1) * (defaultFrameWidth + margin);
                    z = wall === 'north' ? -room.size.depth/2 + 0.1 : room.size.depth/2 - 0.1;
                } else {
                    z = (i - 1) * (defaultFrameWidth + margin);
                    x = wall === 'west' ? -room.size.width/2 + 0.1 : room.size.width/2 - 0.1;
                }
                defaultFrames.push({ x, y, z });
            }
            // 查找与当前位置最接近的画作
            artworksOnWall.forEach(artwork => {
                let closestFrameIndex = -1;
                let minDistance = Infinity;
                defaultFrames.forEach((frame, index) => {
                    let dist = Math.abs(artwork.position.x - frame.x);
                    if ((wall === 'east' || wall === 'west')) {
                        dist = Math.abs(artwork.position.x - frame.z);
                    }
                    if (dist < minDistance) {
                        minDistance = dist;
                        closestFrameIndex = index;
                    }
                });
                if (closestFrameIndex !== -1 && minDistance < (defaultFrameWidth + margin) / 2) {
                    // 创建画作对应的相框
                    let frameWidth = artwork.size.width + 0.2; // 稍微增加一些边框
                    let frameHeight = artwork.size.height + 0.2; // 稍微增加一些边框
                    let x_artwork = artwork.position.x; // 使用画作的位置
                    let y_artwork = artwork.position.y; // 使用画作的位置
                    let z_artwork = 0;
                    if (wall === 'north') z_artwork = -room.size.depth/2 + 0.1;
                    if (wall === 'south') z_artwork = room.size.depth/2 - 0.1;
                    if (wall === 'east') x_artwork = room.size.width/2 - 0.1;
                    if (wall === 'west') x_artwork = -room.size.width/2 + 0.1;
                    // 创建画作对应的相框
                    const geometry_artwork = new THREE.PlaneGeometry(frameWidth, frameHeight);
                    const material_artwork = new THREE.MeshBasicMaterial({ color: 0xFFD39B, side: THREE.DoubleSide });
                    const frame_artwork = new THREE.Mesh(geometry_artwork, material_artwork);
                    frame_artwork.position.set(x_artwork, y_artwork, z_artwork);
                    // 朝向
                    if (wall === 'north') frame_artwork.rotation.y = 0;
                    if (wall === 'south') frame_artwork.rotation.y = Math.PI;
                    if (wall === 'east') frame_artwork.rotation.y = -Math.PI/2;
                    if (wall === 'west') frame_artwork.rotation.y = Math.PI/2;
                    this.scene.add(frame_artwork);
                    // 标记此默认相框位置已被占用
                    defaultFrames[closestFrameIndex].used = true;
                }
            });
            // 创建未被占用的默认相框
            defaultFrames.forEach(frame => {
                if (!frame.used) {
                    // 确定画框的宽高
                    let frameWidth = defaultFrameWidth;
                    let frameHeight = defaultFrameHeight;
                    // 创建画框Mesh
                    const geometry = new THREE.PlaneGeometry(frameWidth, frameHeight);
                    const material = new THREE.MeshBasicMaterial({ color: 0x888888, side: THREE.DoubleSide });
                    const frameMesh = new THREE.Mesh(geometry, material);
                    frameMesh.position.set(frame.x, frame.y, frame.z);
                    // 朝向
                    if (wall === 'north') frameMesh.rotation.y = 0;
                    if (wall === 'south') frameMesh.rotation.y = Math.PI;
                    if (wall === 'east') frameMesh.rotation.y = -Math.PI/2;
                    if (wall === 'west') frameMesh.rotation.y = Math.PI/2;
                    this.scene.add(frameMesh);
                }
            });
        });
        room.artworks.forEach(artwork => {
            // 画作纹理
            const texture = new THREE.TextureLoader().load(artwork.image, 
                () => {texture.encoding = THREE.sRGBEncoding; console.log('Texture loaded:', artwork.image);},
                undefined,
                (err) => {console.error('Texture load error:', artwork.image, err);}
            );
            // 画作本体
            const material = new THREE.MeshBasicMaterial({ 
                map: texture, 
                side: THREE.DoubleSide,
                polygonOffset: true,
                polygonOffsetFactor: -2,
                polygonOffsetUnits: -2
            });
            // 让画作略小于画框前表面，避免重叠
            const artworkPlaneWidth = artwork.size.width - 0.16; // 每边缩小0.08
            const artworkPlaneHeight = artwork.size.height - 0.16;
            const geometry = new THREE.PlaneGeometry(artworkPlaneWidth, artworkPlaneHeight);
            const mesh = new THREE.Mesh(geometry, material);
            mesh.renderOrder = 1; // 画作优先渲染
            // 相框参数
            const frameThickness = 0.08; // 框厚度
            const frameDepth = 0.06; // 框的前后厚度
            const frameWidth = artwork.size.width + frameThickness * 2;
            const frameHeight = artwork.size.height + frameThickness * 2;
            const frameMaterial = new THREE.MeshPhongMaterial({ color: 0xFFD39B, shininess: 30, specular: 0x888888 });
            // 四条边
            const edges = [];
            // 上
            edges.push(new THREE.Mesh(new THREE.BoxGeometry(frameWidth, frameThickness, frameDepth), frameMaterial));
            // 下
            edges.push(new THREE.Mesh(new THREE.BoxGeometry(frameWidth, frameThickness, frameDepth), frameMaterial));
            // 左
            edges.push(new THREE.Mesh(new THREE.BoxGeometry(frameThickness, frameHeight, frameDepth), frameMaterial));
            // 右
            edges.push(new THREE.Mesh(new THREE.BoxGeometry(frameThickness, frameHeight, frameDepth), frameMaterial));
            // 定位
            edges[0].position.set(0, (frameHeight/2 - frameThickness/2), 0); // 上
            edges[1].position.set(0, -(frameHeight/2 - frameThickness/2), 0); // 下
            edges[2].position.set(-(frameWidth/2 - frameThickness/2), 0, 0); // 左
            edges[3].position.set((frameWidth/2 - frameThickness/2), 0, 0); // 右
            // 组合
            const group = new THREE.Group();
            edges.forEach(e => group.add(e));
            mesh.position.z = frameDepth/2 + 0.01; // 画作略前
            group.add(mesh);
            // 挂墙定位
            switch(artwork.position.wall) {
                case 'north':
                    group.position.set(artwork.position.x, artwork.position.y, -room.size.depth/2 + 0.1);
                    break;
                case 'south':
                    group.position.set(artwork.position.x, artwork.position.y, room.size.depth/2 - 0.1);
                    group.rotation.y = Math.PI;
                    break;
                case 'east':
                    group.position.set(room.size.width/2 - 0.1, artwork.position.y, artwork.position.x);
                    group.rotation.y = -Math.PI/2;
                    break;
                case 'west':
                    group.position.set(-room.size.width/2 + 0.1, artwork.position.y, artwork.position.x);
                    group.rotation.y = Math.PI/2;
                    break;
            }
            group.receiveShadow = true;
            group.castShadow = true;
            this.scene.add(group);
            this.artworkMeshes.set(mesh.uuid, artwork);
        });
    }
    clearRoom() {
        // 只移除墙上的画作
        this.artworkMeshes.forEach((artwork, uuid) => {
            const mesh = this.scene.getObjectByProperty('uuid', uuid);
            if (mesh) {
                // mesh.parent 可能是Group
                if (mesh.parent) {
                    this.scene.remove(mesh.parent);
                } else {
                    this.scene.remove(mesh);
                }
            }
        });
        this.artworkMeshes.clear();
    }
    onWindowResize() {
        this.camera.aspect = window.innerWidth / window.innerHeight;
        this.camera.updateProjectionMatrix();
        this.renderer.setSize(window.innerWidth, window.innerHeight);
    }
    // 新增：下一个展厅
    nextRoom() {
        this.currentRoomIndex = (this.currentRoomIndex + 1) % this.data.rooms.length;
        this.createRoom(this.currentRoomIndex);
        // 重置相机朝向和跳跃状态
        this.isJumping = false;
        this.jumpVelocity = 0;
        this.pitch = 0;
        const currentRoom = this.data.rooms[this.currentRoomIndex];
        const centerY = 3.0;
        const northOffset = 1; // 向北偏移5米
        this.camera.position.set(0, centerY, -northOffset);
        this.yaw = Math.PI;
        this.updateCameraRotation();
        // 小人初始化位置也同步
        if (this.avatar) {
            // 重新添加avatar到场景
            if (!this.scene.children.includes(this.avatar)) {
                this.scene.add(this.avatar);
            }
            this.avatar.position.set(0, 0, -northOffset);
            this.avatar.avatarYaw = Math.PI;
            this.avatar.targetAvatarYaw = Math.PI;
            this.avatar.avatar.rotation.y = Math.PI;
        }
        this.camera.fov = 100;
        this.camera.updateProjectionMatrix();
    }
    // 新增：上一个展厅
    previousRoom() {
        this.currentRoomIndex = (this.currentRoomIndex - 1 + this.data.rooms.length) % this.data.rooms.length;
        this.createRoom(this.currentRoomIndex);
        // 重置相机朝向和跳跃状态
        this.isJumping = false;
        this.jumpVelocity = 0;
        this.pitch = 0;
        const currentRoom = this.data.rooms[this.currentRoomIndex];
        const centerY = 3.0;
        const northOffset = 1; // 向北偏移5米
        this.camera.position.set(0, centerY, -northOffset);
        this.yaw = Math.PI;
        this.updateCameraRotation();
        // 小人初始化位置也同步
        if (this.avatar) {
            // 重新添加avatar到场景
            if (!this.scene.children.includes(this.avatar)) {
                this.scene.add(this.avatar);
            }
            this.avatar.position.set(0, 0, -northOffset);
            this.avatar.avatarYaw = Math.PI;
            this.avatar.targetAvatarYaw = Math.PI;
            this.avatar.avatar.rotation.y = Math.PI;
        }
        this.camera.fov = 100;
        this.camera.updateProjectionMatrix();
    }

    // 新增：点击画作弹窗详情
    onCanvasClick(event) {
        // 只处理左键点击
        if (event.button !== 0) return;
        // 计算鼠标在canvas中的归一化坐标
        const rect = this.renderer.domElement.getBoundingClientRect();
        const x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
        const y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
        this.mouse.set(x, y);
        this.raycaster.setFromCamera(this.mouse, this.camera);
        // 收集所有画作mesh
        const meshes = Array.from(this.artworkMeshes.keys()).map(uuid => this.scene.getObjectByProperty('uuid', uuid));
        const intersects = this.raycaster.intersectObjects(meshes, false);
        if (intersects.length > 0) {
            const mesh = intersects[0].object;
            const artwork = this.artworkMeshes.get(mesh.uuid);
            if (artwork) {
                this.showArtworkDetail(artwork);
            }
        }
    }

    // 新增：展示画作详情弹窗
    showArtworkDetail(artwork) {
        let modal = document.getElementById('artwork-modal');
        if (!modal) {
            modal = document.createElement('div');
            modal.id = 'artwork-modal';
            modal.innerHTML = `
                <div class="artwork-modal-content">
                    <span class="artwork-modal-close">&times;</span>
                    <div class="artwork-modal-flex">
                        <img class="artwork-image" src="" alt="artwork" />
                        <div class="artwork-info">
                            <h2 class="artwork-title"></h2>
                            <p class="artwork-artist"></p>
                            <p class="artwork-description"></p>
                        </div>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
            // 关闭按钮
            modal.querySelector('.artwork-modal-close').onclick = () => {
                modal.style.display = 'none';
            };
            // 点击遮罩关闭
            modal.onclick = (e) => { if (e.target === modal) modal.style.display = 'none'; };
            // 样式
            const style = document.createElement('style');
            style.textContent = `
                #artwork-modal {
                    position: fixed; left: 0; top: 0; width: 100vw; height: 100vh;
                    background: rgba(0,0,0,0.45); z-index: 99999; display: flex; align-items: center; justify-content: center;
                }
                .artwork-modal-content {
                    background: #fff; border-radius: 10px; padding: 32px 32px 24px 32px; min-width: 320px; max-width: 90vw; box-shadow: 0 8px 32px rgba(0,0,0,0.18);
                    position: relative;
                }
                .artwork-modal-close {
                    position: absolute; right: 18px; top: 12px; font-size: 28px; color: #888; cursor: pointer; font-weight: bold;
                }
                .artwork-modal-flex {
                    display: flex; flex-direction: row; align-items: flex-start; gap: 32px;
                    width: 100%;
                }
                .artwork-image {
                    display: block;
                    width: 100%;
                    height: auto;
                    max-width: none;
                    max-height: 600px;
                    border-radius: 8px;
                    box-shadow: 0 2px 12px rgba(0,0,0,0.13);
                    background: #f6f6f6;
                    object-fit: contain;
                }
                .artwork-modal-flex > .artwork-image {
                    flex: 0 0 60%;
                    min-width: 0;
                    min-height: 0;
                    margin-right: 0;
                }
                .artwork-info {
                    flex: 0 0 40%;
                    min-width: 0;
                    padding-left: 18px;
                    display: flex;
                    flex-direction: column;
                    justify-content: flex-start;
                }
                .artwork-title { font-size: 22px; margin: 0 0 10px 0; color: #222; }
                .artwork-artist { font-size: 16px; color: #666; margin: 0 0 10px 0; }
                .artwork-description { font-size: 15px; color: #444; margin: 0; }
            `;
            document.head.appendChild(style);
        }
        modal.querySelector('.artwork-title').textContent = artwork.title || '';
        modal.querySelector('.artwork-artist').textContent = artwork.artist ? `作者：${artwork.artist}` : '';
        modal.querySelector('.artwork-description').textContent = artwork.description || '';
        modal.querySelector('.artwork-image').src = artwork.image || '';
        modal.style.display = 'flex'; 
    }

    // 新增：设置小人显示/隐藏
    setAvatarVisible(visible) {
        if (this.avatar) {
            this.avatar.visible = visible;
        }
    }
}

export { Gallery };